<template>
  <div class="product-detail-page">
    <!-- 商品图片区域 -->
    <div class="product-gallery">
      <div class="gallery-main">
        <img :src="product.image" :alt="product.name" class="product-image" />
      </div>
    </div>

    <!-- 商品基本信息 -->
    <div class="product-info-section">
      <div class="product-header">
        <h1 class="product-title">{{product.name}}</h1>

      </div>

      <!-- 价格信息 -->
      <div class="price-section">
        <div class="points-price">
          <span class="points-label">所需积分</span>
          <span class="points-value">{{product.points}}</span>
          <span class="points-unit">积分</span>
        </div>
        <div class="cash-price" v-if="product.originalPrice || product.price">
          <div class="original-price" v-if="product.originalPrice">
            <span class="price-label">原价</span>
            <span class="price-value">¥{{product.originalPrice}}</span>
          </div>
          <div class="current-price" v-if="product.price">
            <span class="price-label">现价</span>
            <span class="price-value">¥{{product.price}}</span>
          </div>
        </div>
      </div>

      <!-- 商品标签 -->
      <div class="product-tags">
        <span class="tag stock-tag">库存 {{product.stock}}件</span>
        <span class="tag status-tag" :class="getStatusClass(product.state)">
          {{getStatusText(product.state)}}
        </span>
        <span class="tag type-tag" v-if="product.type">{{getTypeText(product.type)}}</span>
      </div>
    </div>

    <!-- 兑换数量选择区域 -->
    <div class="quantity-section" v-if="from === 'pointsMall' && product.stock > 0">
      <div class="section-header">
        <h3>兑换数量</h3>
      </div>
      <div class="quantity-content">
        <div class="quantity-selector">
          <span class="quantity-label">选择数量</span>
          <div class="quantity-controls">
            <button
              class="quantity-btn minus"
              @click="decreaseQuantity"
              :disabled="exchangeQuantity <= 1"
            >-</button>
            <input
              type="number"
              class="quantity-input"
              v-model.number="exchangeQuantity"
              :min="1"
              :max="product.stock"
              @change="validateQuantity"
            >
            <button
              class="quantity-btn plus"
              @click="increaseQuantity"
              :disabled="exchangeQuantity >= product.stock"
            >+</button>
          </div>
          <span class="quantity-hint">库存: {{product.stock}} 件</span>
        </div>
        <div class="total-points">
          <span class="total-label">总计积分</span>
          <span class="total-value">{{product.points * exchangeQuantity}} 积分</span>
        </div>
      </div>
    </div>

    <!-- 商品详情区域 -->
    <div class="product-detail-section">
      <div class="section-header">
        <h3>商品详情</h3>
      </div>
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">商品描述</span>
          <span class="detail-value">{{product.description}}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">商品类型</span>
          <span class="detail-value">{{getTypeText(product.type)}}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">库存数量</span>
          <span class="detail-value">{{product.stock}} 件</span>
        </div>
        <div class="detail-item" v-if="product.createTime">
          <span class="detail-label">上架时间</span>
          <span class="detail-value">{{formatTime(product.createTime)}}</span>
        </div>
        <div class="detail-item" v-if="product.updateTime">
          <span class="detail-label">更新时间</span>
          <span class="detail-value">{{formatTime(product.updateTime)}}</span>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-action-bar">
      <div class="action-content">
        <div class="price-display">
          <span class="points-display">{{product.points * exchangeQuantity}}</span>
          <span class="points-text">积分</span>
        </div>
        <button class="buy-button" @click="handleBuy" :disabled="product.stock <= 0">
          {{product.stock <= 0 ? '已售罄' : '立即兑换'}}
        </button>
      </div>
    </div>


    <OrderModel ref="OrderModel" @reload="reLoad" v-if="result.type == 1 && from !== 'pointsMall'" />
  </div>
</template>

<script>
import OrderModel from '@/components/orderModel.vue'
import { Dialog, Toast } from 'vant'

export default {
  components: {OrderModel},
  data() {
    return {
      id: '',
      from: '',
      result: {},
      product: {},
      currentStudent: null,
      exchangeQuantity: 1 // 兑换数量，默认为1
    }
  },
  created() {
    console.log('商品详情页面加载:', this.$route)
    this.id = this.$route.params.id
    this.from = this.$route.params.from ? this.$route.params.from : ''
    // 获取路由参数中的学生信息，如果没有则从缓存中获取
    this.currentStudent = this.$route.params.studentInfo || this.getStudentInfoFromStorage()

    // 保存学生信息到缓存
    if (this.currentStudent) {
      this.saveStudentInfoToStorage(this.currentStudent)
    }

    console.log('商品详情页面参数:', {
      id: this.id,
      from: this.from,
      studentInfo: this.currentStudent,
      timestamp: new Date().toISOString()
    })

    if (this.from === 'pointsMall') {
      this.loadProductData()
    } else {
      this.getData()
    }
  },
  methods: {
    reLoad() {
      this.getData()
    },
    getData() {
      this.$http.getCourseDetail({id: this.id, openId: localStorage.getItem('px_user_openid')}).then(res => {
        console.log(res)
        this.result = res.data.result

      }).catch(err => {
        console.log(err, 'err')
        this.$toast(err.data.message)
      })
    },
    async loadProductData() {
      try {
        console.log('开始加载商品详情:', {
          id: this.id,
          studentInfo: this.currentStudent,
          timestamp: new Date().toISOString()
        })

        // 准备请求参数 - 调用 /wx/goods/detail 接口，上送 id 字段
        const params = {
          id: this.id
        }

        // 调用商品详情接口
        const response = await this.$http.getGoodsDetail(params)

        if (response.data.code === 200 && response.data.result) {
          // 接口返回成功，使用接口数据
          const goodsDetail = response.data.result
          this.product = {
            id: goodsDetail.id,
            name: goodsDetail.goodsName,
            description: goodsDetail.goodsDescription || '',
            points: goodsDetail.goodsPoints || 0,
            stock: goodsDetail.goodsNumber || 0,
            image: goodsDetail.goodsImg || require('@/assets/shouqin.png'),
            originalPrice: goodsDetail.goodsOriginalPrice,
            price: goodsDetail.goodsPrice,
            state: goodsDetail.goodsState,
            depId: goodsDetail.depId,
            type: goodsDetail.goodsType,
            createTime: goodsDetail.createTime,
            updateTime: goodsDetail.updateTime
          }

          console.log('商品详情加载成功:', {
            id: this.id,
            product: this.product,
            timestamp: new Date().toISOString()
          })
        } else {
          // 接口返回失败，显示错误信息
          console.error('商品详情接口返回失败:', {
            id: this.id,
            responseCode: response.data.code,
            message: response.data.message,
            timestamp: new Date().toISOString()
          })
          Toast.fail(response.data.message || '获取商品详情失败')
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        Toast.fail('获取商品详情失败，请检查网络连接')
      }
    },
    // 减少兑换数量
    decreaseQuantity() {
      if (this.exchangeQuantity > 1) {
        this.exchangeQuantity--
      }
    },

    // 增加兑换数量
    increaseQuantity() {
      if (this.exchangeQuantity < this.product.stock) {
        this.exchangeQuantity++
      }
    },

    // 验证兑换数量
    validateQuantity() {
      if (this.exchangeQuantity < 1) {
        this.exchangeQuantity = 1
      } else if (this.exchangeQuantity > this.product.stock) {
        this.exchangeQuantity = this.product.stock
        Toast('兑换数量不能超过库存数量')
      }
    },

    handleBuy() {
      if (this.from === 'pointsMall') {
        // 验证兑换数量是否超过库存
        if (this.exchangeQuantity > this.product.stock) {
          Toast('兑换数量不能超过库存数量')
          return
        }

        // 验证兑换数量是否小于1
        if (this.exchangeQuantity < 1) {
          Toast('兑换数量至少为1')
          return
        }

        const totalPoints = this.product.points * this.exchangeQuantity
        Dialog.confirm({
          title: '确认兑换',
          message: `确定要花费 ${totalPoints} 积分兑换 ${this.exchangeQuantity} 件 ${this.product.name} 吗？`,
          confirmButtonText: '确认兑换',
          cancelButtonText: '取消'
        }).then(() => {
          // 调用购买接口
          const params = {
            studentId: this.currentStudent?.id, // 学生ID
            itemId: this.product.id, // 物品ID
            purchaseQuantity: this.exchangeQuantity // 兑换数量
          }

          console.log('调用购买接口参数:', params)

          // 调用 /wx/purchase/buy 接口
          this.$http.buyGoods(params).then(response => {
            console.log('购买接口响应:', response)
            if (response.data.code === 200) {
              Toast.success('兑换成功！')
              // 购买成功后跳转到物品列表页
              setTimeout(() => {
                this.$router.back()
              }, 1500)
            } else {
              // 接口正常返回但业务逻辑错误，显示后端返回的具体错误信息
              Toast.fail(response.data.message || '兑换失败，请重试')
            }
          }).catch(error => {
            console.error('兑换失败:', error)
            // 详细打印错误对象结构以便调试
            console.log('错误对象结构:', {
              error: error,
              errorData: error.data,
              errorResponse: error.response,
              errorMessage: error.message
            })

            // 检查是否是业务逻辑错误（从axios拦截器reject的响应）
            if (error && error.data) {
              // axios拦截器reject的响应，包含后端返回的具体错误信息
              const errorData = error.data
              Toast.fail(errorData.message || '兑换失败，请重试')
            }
            // 检查是否是HTTP错误响应
            else if (error.response && error.response.data) {
              // 后端返回了HTTP错误响应，显示具体的错误信息
              const errorData = error.response.data
              Toast.fail(errorData.message || '兑换失败，请重试')
            } else if (error.message) {
              // 其他类型的错误
              Toast.fail(error.message || '兑换失败，请重试')
            } else {
              // 真正的网络连接错误
              Toast.fail('兑换失败，请检查网络连接')
            }
          })
        }).catch(() => {
          // 取消购买
        })
      }
    },
    orderCourse(e) {
      if (e == null) {
        this.$refs.OrderModel.show = true
        this.$refs.OrderModel.id = this.id
      }
    },
    // 保存学生信息到缓存
    saveStudentInfoToStorage(studentInfo) {
      try {
        localStorage.setItem('currentStudentInfo', JSON.stringify(studentInfo))
        console.log('学生信息已保存到缓存:', studentInfo)
      } catch (error) {
        console.error('保存学生信息到缓存失败:', error)
      }
    },
    // 从缓存获取学生信息
    getStudentInfoFromStorage() {
      try {
        const studentInfo = localStorage.getItem('currentStudentInfo')
        if (studentInfo) {
          const parsedInfo = JSON.parse(studentInfo)
          console.log('从缓存获取学生信息:', parsedInfo)
          return parsedInfo
        }
      } catch (error) {
        console.error('从缓存获取学生信息失败:', error)
      }
      return null
    },

    // 获取商品状态文本
    getStatusText(state) {
      const statusMap = {
        '0': '上架',
        '1': '下架',
        '2': '缺货'
      }
      return statusMap[state] || '未知状态'
    },

    // 获取商品状态样式类
    getStatusClass(state) {
      const statusClassMap = {
        '0': 'status-online',
        '1': 'status-offline',
        '2': 'status-out-of-stock'
      }
      return statusClassMap[state] || 'status-unknown'
    },

    // 获取商品类型文本
    getTypeText(type) {
      const typeMap = {
        '1': '文具用品',
        '2': '玩具',
        '3': '优惠券',
        '4': '体验课'
      }
      return typeMap[type] || '其他商品'
    },

    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return ''
      try {
        const date = new Date(timeString)
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        return timeString
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail-page {
  height: 100vh;
  background: #f8f9fa;
  padding-bottom: 80px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
}

/* 商品图片区域 */
.product-gallery {
  width: 100%;
  height: 220px;
  background: #fff;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .gallery-main {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;

    .product-image {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
      border-radius: 6px;
    }
  }
}

/* 商品基本信息区域 */
.product-info-section {
  background: #fff;
  padding: 20px 16px;
  margin-bottom: 8px;

  .product-header {
    margin-bottom: 16px;

    .product-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
      margin-bottom: 8px;
    }

    .product-subtitle {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }
  }

  .price-section {
    margin-bottom: 16px;

    .points-price {
      display: flex;
      align-items: baseline;
      margin-bottom: 8px;

      .points-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
      }

      .points-value {
        font-size: 24px;
        font-weight: 700;
        color: #ff6b6b;
        margin-right: 4px;
      }

      .points-unit {
        font-size: 14px;
        color: #ff6b6b;
      }
    }

    .cash-price {
      display: flex;
      gap: 16px;

      .original-price,
      .current-price {
        display: flex;
        align-items: center;

        .price-label {
          font-size: 12px;
          color: #999;
          margin-right: 4px;
        }

        .price-value {
          font-size: 14px;
          color: #999;
        }
      }

      .original-price .price-value {
        text-decoration: line-through;
      }

      .current-price .price-value {
        color: #ff6b6b;
        font-weight: 500;
      }
    }
  }

  .product-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .tag {
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 500;

      &.stock-tag {
        background: #e8f4ff;
        color: #1890ff;
      }

      &.status-tag {
        &.status-online {
          background: #e8f5e8;
          color: #52c41a;
        }

        &.status-offline {
          background: #f5f5f5;
          color: #999;
        }

        &.status-out-of-stock {
          background: #fff2e8;
          color: #fa8c16;
        }

        &.status-unknown {
          background: #f5f5f5;
          color: #666;
        }
      }

      &.type-tag {
        background: #f0f0f0;
        color: #666;
      }
    }
  }
}

/* 兑换数量选择区域 */
.quantity-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .section-header {
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .quantity-content {
    .quantity-selector {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .quantity-label {
        font-size: 14px;
        color: #666;
        min-width: 80px;
      }

      .quantity-controls {
        display: flex;
        align-items: center;
        gap: 8px;

        .quantity-btn {
          width: 32px;
          height: 32px;
          border: 1px solid #ddd;
          background: #fff;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover:not(:disabled) {
            background: #f5f5f5;
            border-color: #ccc;
          }

          &:active:not(:disabled) {
            background: #e8e8e8;
          }

          &:disabled {
            background: #f9f9f9;
            color: #ccc;
            cursor: not-allowed;
          }

          &.minus {
            color: #ff6b6b;
          }

          &.plus {
            color: #52c41a;
          }
        }

        .quantity-input {
          width: 60px;
          height: 32px;
          border: 1px solid #ddd;
          border-radius: 4px;
          text-align: center;
          font-size: 14px;
          font-weight: 500;
          background: #fff;
          color: #333; /* 确保文字颜色可见 */

          &:focus {
            outline: none;
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
          }

          &::-webkit-outer-spin-button,
          &::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }

          &[type=number] {
            -moz-appearance: textfield;
          }
        }
      }

      .quantity-hint {
        font-size: 12px;
        color: #999;
        margin-left: 12px;
      }
    }

    .total-points {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-top: 1px solid #f8f8f8;

      .total-label {
        font-size: 14px;
        color: #666;
        font-weight: 500;
      }

      .total-value {
        font-size: 18px;
        color: #ff6b6b;
        font-weight: 700;
      }
    }
  }
}

/* 商品详情区域 */
.product-detail-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;

  .section-header {
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .detail-content {
    .detail-item {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 12px 0;
      border-bottom: 1px solid #f8f8f8;

      &:last-child {
        border-bottom: none;
      }

      .detail-label {
        font-size: 14px;
        color: #666;
        min-width: 80px;
      }

      .detail-value {
        font-size: 14px;
        color: #333;
        text-align: right;
        flex: 1;
        margin-left: 16px;
        line-height: 1.5;
      }
    }
  }
}

/* 底部操作栏 */
.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 8px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);

  .action-content {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .price-display {
      display: flex;
      align-items: baseline;

      .points-display {
        font-size: 20px;
        font-weight: 700;
        color: #ff6b6b;
        margin-right: 4px;
      }

      .points-text {
        font-size: 14px;
        color: #ff6b6b;
      }
    }

    .buy-button {
      flex: 1;
      max-width: 200px;
      height: 44px;
      background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
      border: none;
      border-radius: 22px;
      color: #fff;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: linear-gradient(135deg, #ff5252, #ff7b7b);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
      }

      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 6px rgba(255, 107, 107, 0.3);
      }

      &:disabled {
        background: #ccc;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
    }
  }
}

/* 课程详情部分（保持原有样式） */
.course-section {
  .top_card {
    width: 100%;
    box-shadow: 0 4px 15px 0 rgba(0,0,0,0.09);
    border-radius: 4px;
    background: #fff;
    padding: 20px 20px 10px;
    box-sizing: border-box;

    .records_item_title {
      width: 100%;
      height: auto;
      margin-bottom: 10px;
      text-align: center;
      color: #09122B;
      font-weight: 700;
      font-size: 18px;
    }

    .records_item_detail {
      .shengyu {
        .detail_title {
          font-size: 14px;
          color: #666;
        }

        .num {
          font-size: 20px;
          font-weight: bold;
        }
      }
    }
  }

  .bottom {
    width: calc(100% - 40px);
    height: 44px;
    margin: 10px 20px 40px;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

/* 响应式设计 */
@media (max-width: 375px) {
  .product-info-section {
    padding: 16px 12px;

    .product-header .product-title {
      font-size: 16px;
    }

    .price-section .points-price .points-value {
      font-size: 22px;
    }
  }

  .bottom-action-bar {
    padding: 8px 12px;

    .action-content .price-display .points-display {
      font-size: 18px;
    }
  }
}
</style>
